package com.CMUBiS.PageServlets;
import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import com.CMUBiS.Data.Error;
import com.CMUBiS.Data.Footer;
import com.CMUBiS.Data.GlobalVars;
import com.CMUBiS.Data.Header;
import com.CMUBiS.PageControllers.*;
import com.CMUBiS.util.Bid;
import com.CMUBiS.util.Item;
import com.CMUBiS.util.StopWatch;

/**
 * This servlet is the user account
 *
 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
 * @version 0.1
 * @since 0.1
 * @date 04/05/2011
 *
 */
@WebServlet(name="MyAccountServlet", urlPatterns="/myaccount") public class MyAccountServlet extends HttpServlet {

	private static final long serialVersionUID = 6475041006628458743L;
	private static final String EMPTY = "";
	private static final String title = "My Account";
	private static final GlobalVars GV = new GlobalVars();

	/**
	 * Get the page, calls the page to be made
	 * We used to check the parameters in here, but I moved it to a controller object to keep the logic away from the layout
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
		makePage(request, response, Boolean.FALSE);
	}

	/**
	 * Get the page, we can just pass this to doPost since the client generator will be posting userIDs and authTokens all the time
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
		this.makePage(request, response, Boolean.TRUE);
	}

	/**
	 * This method starts the page timer, writes the header, creates the HTML for the page, writes the stats, and the footer
	 *
	 * @param request The incoming user request
	 * @param response  The out going user response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void makePage(HttpServletRequest request, HttpServletResponse response, Boolean isGet)  throws ServletException, IOException {
		if(request !=null && response != null){
			// Do the timer if we are collecting stats
			StopWatch timer;
			if(GlobalVars.collectStats){
				timer = new StopWatch();
				timer.start();
			}

			// Create a new page controller for this page, it will get and process the data
			MyAccountController vars = new MyAccountController();
			vars.checkInputs(request);

			// We are using PrintWriter to be friendly to the international community. PrintWrite auto-converts coding
			PrintWriter out = response.getWriter();

			// Set the return type
			response.setContentType("text/html");

			// Write the page header
			Header.writeHeader(out, title, vars.getUserIDString(), vars.getAuthTokenString());

			// If the output is to be suppressed then we'll redirect the output
			if(vars.getSuppressOutput())
				out = new PrintWriter(GlobalVars.blackHole);

			// Do HTML4 or 5 depending on the global variables
			if(GlobalVars.isHTML4)
				createHTML4(out, vars, isGet);
			else
				createHTML5(out, vars, isGet);

			// Redirect the output to start writing the the user again in case we were putting it in the black hole
			out = response.getWriter();

			/*
			 * Output any errors. These don't need to be too pretty since we hope there isn't any!
			 * We put them here to help with debug and info, the page above should show pretty ones for users
			 */
			if(GlobalVars.printAllErrors){
				out.println("<BR />Errors: " + vars.getErrors().size());
				for(Error error: vars.getErrors())
					out.println("<BR />" + error.getErrorNumber() + " " +error.toString());
			}

			/*
			 * Process the page time
			 */
			if(GlobalVars.collectStats){
				timer.stop();
				vars.setTotalTime(timer.getTimeTaken());
				GlobalVars.addStats(request, out, vars);
			}

			// Write the page footer
			Footer.writeFooter(out);
		}
	}

	/**
	 * Creates the HTML4 version of the website
	 *
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML4(PrintWriter out, MyAccountController vars, Boolean isGet){
		if(out != null && vars != null)
			try{
				// Get the data needed to display the page
				vars.getHTML4Data();
				vars.processHTML4();

				// Print links available from user account screen
				out.println(vars.getUpdateUserDetailsURL());

				// Print the welcome message
				if(vars.getWelcomeMessage() != null){
					out.println(vars.getWelcomeMessage());
					out.println("<BR />");
				}

				/*
				 *  Print the items the user is currently bidding on
				 */
				out.println("Currently Bidding Items");
				out.println("<BR />");
				if(vars.getCurrentBids() != null && vars.getCurrentBiddingItemURLs()!=null){
					ArrayList<Bid> currentBids = vars.getCurrentBids();
					String[] items = vars.getCurrentBiddingItemURLs();
					int length = items.length;

					for(int i=0; i< length; i++){
						Item tempItem = currentBids.get(i).getItem();
						out.println("<div id=\"entry\">");
						out.print("<label for=\"currentBids");out.print(tempItem.getID()); out.print("\">");
						out.println(items[i]);
						
						out.println(GlobalVars.makeLabel("bid", tempItem.getID()));
						out.println(currentBids.get(i).getBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("maxBid", tempItem.getID()));
						out.println(tempItem==null ? "missing" : currentBids.get(i).getMaxBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("endDate", tempItem.getID()));
						out.println(tempItem==null ? "missing" : tempItem.getEndDate());
						out.println("</label>");
						
						out.println("</label>");
						out.println("<BR />");
						out.println("</div>");
					}
				}
				else{
					out.println("No Current Bids<BR />");
				}

				// Print the items the user has previously bid on
				out.println("Previous Bids");
				out.println("<BR />");
				if(vars.getOldBids() != null && vars.getOldBiddingItemURLs()!= null){
					ArrayList<Bid> oldBids = vars.getOldBids();
					String[] items = vars.getOldBiddingItemURLs();
					int length = items.length;

					for(int i=0; i< length; i++){
						Item tempItem = oldBids.get(i).getItem();
						out.println("<div id=\"entry\">");
						out.print("<label for=\"previousBids");out.print(tempItem.getID()); out.print("\">");
						out.println(items[i]);
						
						out.println(GlobalVars.makeLabel("bid", tempItem.getID()));
						out.println(oldBids.get(i).getBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("maxBid", tempItem.getID()));
						out.println(tempItem==null ? "missing" : tempItem.getMaxBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("endDate", tempItem.getID()));
						out.println(tempItem==null ? "missing" : tempItem.getEndDate());
						out.println("</label>");
						
						out.println("</label>");
						out.println("<BR />");
						out.println("</div>");
					}
				}
				else{
					out.println("No Old Bids<BR />");
				}

				// Print out the items that the user is currently selling
				out.println("Items Currently Selling");
				out.println("<BR />");
				if(vars.getCurrentSellingItems() != null && vars.getCurrentSellingItemURLs()!= null){
					ArrayList<Item> currentItems = vars.getCurrentSellingItems();
					String[] items = vars.getCurrentSellingItemURLs();
					int length = items.length;

					for(int i=0; i< length; i++){
						out.println("<div id=\"entry\">");
						out.print("<label for=\"currentlySelling");out.print(currentItems.get(i).getID());out.print("\">");
						out.println(items[i]);
						
						out.println(GlobalVars.makeLabel("maxBid", currentItems.get(i).getID()));
						out.println(currentItems.get(i).getMaxBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("endDate", currentItems.get(i).getID()));
						out.println(currentItems.get(i).getEndDate());
						out.println("</label>");
						
						out.println("</label>");
						out.println("<BR />");
						out.println("</div>");
					}
				}
				else{
					out.println("Not Currently Selling<BR />");
				}

				// Print out the items that the user is previously sold
				out.println("Items Previously Sold");
				out.println("<BR />");
				if(vars.getOldSellingItems() != null && vars.getOldSellingItemURLs()!= null){
					ArrayList<Item> oldItems = vars.getOldSellingItems();
					String[] items = vars.getOldSellingItemURLs();
					int length = items.length;

					for(int i=0; i< length; i++){
						out.println("<div id=\"entry\">");
						out.print("<label for=\"previouslySold");out.print(oldItems.get(i).getID()); out.print("\">");
						out.println(items[i]);
						
						out.println(GlobalVars.makeLabel("maxBid", oldItems.get(i).getID()));
						out.println(oldItems.get(i).getMaxBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("endDate", oldItems.get(i).getID()));
						out.println(oldItems.get(i).getEndDate());
						out.println("</label>");
						
						out.println("</label>");
						out.println("<BR />");
						out.println("</div>");
					}
				}
				else{
					out.println("No Previously Sold Items<BR />");
				}

			}
		catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * Creates the HTML5 version of the website
	 *
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML5(PrintWriter out, MyAccountController vars, Boolean isGet){
		if(out != null && vars != null)
			try{
				// Get the data needed to display the page
				vars.getHTML5Data();
				vars.processHTML5();
				// Print links available from user account screen
				out.println(vars.getUpdateUserDetailsURL());

				// Print the welcome message
				if(vars.getWelcomeMessage() != null){
					out.println(vars.getWelcomeMessage());
					out.println("<BR />");
				}

				// Print the items the user is currently bidding on
				out.println("Currently Bidding Items");
				out.println("<BR />");
				if(vars.getCurrentBids() != null && vars.getCurrentBiddingItemURLs()!=
null){
					ArrayList<Bid> currentBids = vars.getCurrentBids();
					String[] items = vars.getCurrentBiddingItemURLs();
					int length = items.length;

					for(int i=0; i< length; i++){
						out.println("<div id=\"entry\">");
						out.print("<label for=\"currentBids");out.print(currentBids.get(i).getItem().getID()); out.print("\">");
						out.println(items[i]);
						out.println(GlobalVars.makeLabel("bid", currentBids.get(i).getItem().getID()));
						out.println(currentBids.get(i).getBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("maxBid", currentBids.get(i).getItem().getID()));
						out.println(currentBids.get(i).getItem()==null ? "missing" : currentBids.get(i).getMaxBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("endDate", currentBids.get(i).getItem().getID()));
						out.println(currentBids.get(i).getItem()==null ? "missing" : currentBids.get(i).getItem().getID());
						out.println("</label>");
						out.println("</label>");
						out.println("<BR />");
						out.println("</div>");
					}
				}
				else{
					out.println("No Current Bids<BR />");
				}

				// Print the items the user has previously bid on
				out.println("Previous Bids");
				out.println("<BR />");
				if(vars.getOldBids() != null && vars.getOldBiddingItemURLs()!= null){
					ArrayList<Bid> oldBids = vars.getOldBids();
					String[] items = vars.getOldBiddingItemURLs();
					int length = items.length;

					for(int i=0; i< length; i++){
						Item tempItem = oldBids.get(i).getItem();
						out.println("<div id=\"entry\">");
						out.print("<label for=\"previousBids");out.print(i); out.print("\">");
						out.println(items[i]);
						out.println(GlobalVars.makeLabel("bid", tempItem.getID()));
						out.println(oldBids.get(i).getBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("maxBid", tempItem.getID()));
						out.println(tempItem==null ? "missing" : tempItem.getMaxBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("endDate", tempItem.getID()));
						out.println(tempItem==null ? "missing" : tempItem.getEndDate());
						out.println("</label>");
						
						out.println("</label>");
						out.println("<BR />");
						out.println("</div>");
					}
				}
				else{
					out.println("No Old Bids<BR />");
				}

				// Print out the items that the user is currently selling
				out.println("Items Currently Selling");
				out.println("<BR />");
				if(vars.getCurrentSellingItems() != null && vars.getCurrentSellingItemURLs()!= null){
					ArrayList<Item> currentItems = vars.getCurrentSellingItems();
					String[] items = vars.getCurrentSellingItemURLs();
					int length = items.length;

					for(int i=0; i< length; i++){
						out.println("<div id=\"entry\">");
						out.print("<label for=\"currentlySelling");out.print(i);
out.print("\">");
						out.println(items[i]);
						out.println(GlobalVars.makeLabel("maxBid", currentItems.get(i).getID()));
						out.println(currentItems.get(i).getMaxBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("endDate", currentItems.get(i).getID()));
						out.println(currentItems.get(i).getEndDate());
						out.println("</label>");
						out.println("</label>");
						out.println("<BR />");
						out.println("</div>");
					}
				}
				else{
					out.println("Not Currently Selling<BR />");
				}

				// Print out the items that the user is previously sold
				out.println("Items Previously Sold");
				out.println("<BR />");
				if(vars.getOldSellingItems() != null && vars.getOldSellingItemURLs()!= null){
					ArrayList<Item> oldItems = vars.getOldSellingItems();
					String[] items = vars.getOldSellingItemURLs();
					int length = items.length;

					for(int i=0; i< length; i++){
						out.println("<div id=\"entry\">");
						out.print("<label for=\"previouslySold");out.print(i);
out.print("\">");
						out.println(items[i]);
						out.println(GlobalVars.makeLabel("maxBid", oldItems.get(i).getID()));
						out.println(oldItems.get(i).getMaxBid());
						out.println("</label>");
						
						out.println(GlobalVars.makeLabel("endDate", oldItems.get(i).getID()));
						out.println(oldItems.get(i).getEndDate());
						out.println("</label>");
						out.println("</label>");
						out.println("<BR />");
						out.println("</div>");
					}
				}
				else{
					out.println("Not Currently Selling<BR />");
				}

			}
		catch(Exception e){
			e.printStackTrace();
		}

	}
}



